from rest_framework import serializers
from users.models import CaptchaReg
from django.contrib.auth import get_user_model
from django.utils import timezone
from utitls import captchas
from django.contrib.auth.hashers import make_password

from drf_movie_rimi.settings import EMAIL_CAPTCHA

User = get_user_model()
'''
用户登录验证 用户名和密码的验证
'''


class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=20, help_text='用户名', allow_null=False)
    password = serializers.CharField(max_length=20, help_text='密码', allow_null=False)


'''
用户登录验证 用户名和密码的验证
'''


class UserLoginV2Serializer(serializers.Serializer):
    username = serializers.CharField(max_length=20, help_text='用户名', allow_null=False)
    password = serializers.CharField(max_length=20, help_text='密码', allow_null=False)
    email = serializers.EmailField(help_text='用户邮箱',allow_null=True)
    captcha = serializers.CharField(max_length=6,min_length=6,help_text='邮箱验证码',allow_null=False)


"""
注册验证码
"""


class UserRegisterCaptchaCreateSerializer(serializers.ModelSerializer):
    """
    验证邮箱是否已经被注册了
    """

    def create(self, validated_data):
        email = validated_data['email']
        #验证邮箱是否已经被注册了
        if User.objects.filter(email=email).exists():
            raise serializers.ValidationError('邮箱已经存在')

        #验证是否是发送验证码过于频繁
        expire_time = timezone.now() -timezone.timedelta(minutes=EMAIL_CAPTCHA['delay_time']['register'])

        if CaptchaReg.objects.filter(email=email,add_time__gt=expire_time).exists():
            raise serializers.ValidationError('请稍后再发送邮件')

        return super().create(validated_data)

    def validate(self, attrs):
        captcha = captchas.gen_captcha()
        attrs['captcha'] = captcha
        return super().validate(attrs)

    class Meta:
        model = CaptchaReg
        fields = ('email',)


#验证码升级版##############
class UserInfoSerializer(serializers.ModelSerializer):

    # 这个步骤是专门给你用的,用于你去修改已经验证好的数据,大前提是你的数据通过验证了
    # 才去做定制化
    def validate(self, attrs):
        attrs['password'] = make_password(attrs['password'])
        email = attrs['email']
        captcha = attrs['captcha']
        validation_time = timezone.now() - timezone.timedelta(seconds=300)
        res = CaptchaReg.objects.filter(email=email, captcha=captcha, add_time__gte=validation_time).exists()
        if not res:
            raise serializers.ValidationError({'error': '验证码错误,或者失效'})
        del (attrs['captcha'])
        return super().validate(attrs)

    email = serializers.EmailField()
    #
    # write_only = True  数据不会在serializer.save()的时候做操作
    # read_only=True  只读数据, 不用去写入数据,只在最后返回的之后显示数据
    captcha = serializers.CharField(max_length=6, min_length=6, write_only=True)

    class Meta:
        model = User
        fields = ("username", 'password', 'email', 'captcha')


class CaptchaRegSerializer(serializers.ModelSerializer):

    def validate(self, attrs):
        email = attrs['email']
        if User.objects.filter(email=email):
            raise serializers.ValidationError({'error': '邮箱已经存在'})
        captcha = captchas.gen_captcha()
        attrs['captcha'] = captcha
        return super().validate(attrs)

    class Meta:
        model = CaptchaReg
        fields = ("email",)

